using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

using Acrobat;

using AKMII.DMRA.Business.Management;
using AKMII.DMRA.Business.Rule;
using AKMII.DMRA.Business.Service;
using AKMII.DMRA.Common;
using AKMII.DMRA.DataAccess;
using AKMII.DMRA.Service;

using iTextSharp.text;
using iTextSharp.text.pdf;

using Microsoft.Office.Interop.Excel;

using Constants = AKMII.DMRA.Common.Constants;
using Starksoft.Cryptography.OpenPGP;

namespace AKMII.DMRA.Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Constants.LogConfigFile = ConfigurationManager.AppSettings["logging.config"];

            if (args != null && args.Count() > 0)
            {
                if (args[0] == "optimize")
                {
                    OptimizeLead();
                }
                else if (args[0] == "report")
                {
                    GenerateReport();
                }
                else if (args[0] == "merge")
                {
                    ScanFolder(ConfigurationManager.AppSettings["ReportPath"]);
                }
                else if (args[0] == "mergetxt")
                {
                    MergeTxt(ConfigurationManager.AppSettings["ReportPath"]);
                }
                else if (args[0] == "summaryreport")
                {
                    SendSummaryReportPerMD();
                }
                else if (args[0] == "rotate")
                {
                    string[] files = Directory.GetFiles(ConfigurationManager.AppSettings["ReportPath"], "*.pdf", SearchOption.AllDirectories);
                    foreach (var file in files)
                    {
                        Utility.ExtractPages(file, file.Replace(".pdf", "_tmp.pdf"));
                        File.Delete(file);
                    }
                }
                else if (args[0] == "powername")
                {
                    string[] files = Directory.GetFiles(ConfigurationManager.AppSettings["PowerNamePath"], "*.xls");

                    PowerAccesor accessor = new PowerAccesor();
                    accessor.DeletePowerNameTable();

                    foreach (var file in files)
                    {
                        Logger.Info("Begin to process " + file);

                        List<string> paths = ConvertToCSV(file);

                        foreach (var csvFile in paths)
                        {
                            List<PowerName> names = GetPowerNameData(csvFile);

                            if (names != null && names.Count > 0)
                            {
                                accessor.InsertPowerName(names);
                            }
                        }

                        Logger.Info("End to process " + file);
                    }
                }
                else if (args[0] == "mail")
                {
                    Logger.Info("Start send confirmation mail for DMRA file");
                    Mail email = new Mail();
                    LeadBlock zip = new ZipAccessor().GetLeadBlcokTypesCountForTest(CurrentPeriod.Year.ToString(), CurrentPeriod.Month.ToString());

                    StringBuilder text = new StringBuilder(string.Empty);
                    text.Append("ActiveCount: " + zip.ActiveLeadCount.ToString() + "\r\n");
                    text.Append("LapsedCount: " + zip.LapsedLeadCount.ToString() + "\r\n");
                    text.Append("BusinessCount: " + zip.BusinessLeadCount.ToString() + "\r\n");
                    text.Append("NeighborCount: " + zip.NeighborLeadCount.ToString() + "\r\n");
                    text.Append("TotalCount: " + (zip.NeighborLeadCount + zip.BusinessLeadCount + zip.ActiveLeadCount + zip.LapsedLeadCount).ToString() + "\r\n");

                    email.Subject = string.Format("Orders summary Informaton for {0} test markets",
                        Utility.GetMonthName(CurrentPeriod.Month) + "&" + CurrentPeriod.Year);
                    email.Content = string.Format("The order period for {0} is complete and the order file had been uploaded to the printer successfully. The totals for the order were:\n{1}",
                        Utility.GetMonthName(CurrentPeriod.Month), text.ToString());
                    List<string> mailAddress = new List<string>();

                    foreach (string address in "Scott.Kretschmar@combined.com;tomc@integrapds.com;mikes@dmrainc.com".Split(';'))
                    {
                        mailAddress.Add(address);
                    }

                    email.Recipients = mailAddress;
                    SmtpMailService mailService = new SmtpMailService(SystemConfiguration.CommonSetting.SmtpServer,
                        SystemConfiguration.CommonSetting.SystemMailAddress, SystemConfiguration.CommonSetting.MailPassword);
                    mailService.Send(email);
                    Logger.Info("Finish send confirmation mail for DMRA file");

                }
                else if (args[0] == "pdfmail")
                {
                    Logger.Info("Start send confirmation mail for printer file");
                    Mail email = new Mail();

                    email.Subject = string.Format("The PDF of {0} were generated and sent to printer FTP",
                         Utility.GetMonthName(CurrentPeriod.Month) + "&" + CurrentPeriod.Year);
                    email.Content = string.Empty;
                    List<string> mailAddress = new List<string>();

                    foreach (string address in "Scott.Kretschmar@combined.com;akey@microdg.com;jyounger@microdg.com;atchison_sean@hotmail.com;chris.li@akmii.com".Split(';'))
                    {
                        mailAddress.Add(address);
                    }

                    email.Recipients = mailAddress;
                    SmtpMailService mailService = new SmtpMailService(SystemConfiguration.CommonSetting.SmtpServer,
                        SystemConfiguration.CommonSetting.SystemMailAddress, SystemConfiguration.CommonSetting.MailPassword);
                    mailService.Send(email);

                    Logger.Info("Finish send confirmation mail for printer file");

                }
                else
                {
                    //Nothing to do
                }
            }
            else
            {
                //Nothing to do
            }
        }

        private static void OptimizeLead()
        {
            string mds = ConfigurationManager.AppSettings["Name"];
            int month = 0;
            int year = 0;

            GetMonthAndYear(out month, out year);

            Logger.Info("Current month is " + month.ToString("D2") + year.ToString());

            const string dmraFileNameOfBase = "Base_{0}_{1}{2}.txt";
            const string dmraFileNameOfPros = "Pros_{0}_{1}{2}.txt";
            const string histFileName = "OrderHist_{0}_{1}{2}.txt";

            LeadManager leadManager = new LeadManager();
            AccountManager accountManager = new AccountManager();
            MappointService mappoint = null;

            foreach (var md in mds.Split(','))
            {
                int number = 0;
                Logger.Info("Start optmize lead for " + md);

                List<Lead> leads = leadManager.GetLeads(md, month, year);

                Logger.Info(leads.Count);
                List<Agent> agents = accountManager.GetAgents(md);
                List<Lead> fullLeadsForDetailReport = new List<Lead>();

                var assignmentGroup = leads.GroupBy(c => c.UserId);

                if (bool.Parse(ConfigurationManager.AppSettings["IsGenerateDMRA"]))
                {
                    mappoint = new MappointService();
                    FileStream basefs = new FileStream(Path.Combine(ConfigurationManager.AppSettings["ReportPath"], string.Format(dmraFileNameOfBase, md, month.ToString("D2"), year)), FileMode.Create);
                    FileStream prosfs = new FileStream(Path.Combine(ConfigurationManager.AppSettings["ReportPath"], string.Format(dmraFileNameOfPros, md, month.ToString("D2"), year)), FileMode.Create);
                    FileStream fs = new FileStream(Path.Combine(ConfigurationManager.AppSettings["ReportPath"], string.Format(histFileName, md, month.ToString("D2"), year)),
                                FileMode.Create);
                    StreamWriter basesw = new StreamWriter(basefs);
                    StreamWriter prossw = new StreamWriter(prosfs);
                    StreamWriter histsw = new StreamWriter(fs);

                    foreach (var assignmentItem in assignmentGroup)
                    {
                        if (!string.IsNullOrEmpty(assignmentItem.Key) && assignmentItem.Count() > 0)
                        {
                            //if (assignmentItem.Key != "2 TREVOR THOMPSON")
                            //{
                            //    Logger.Info("Skip for " + assignmentItem.Key);
                            //    continue;
                            //}
                            //ExcelReportService oldexcelService = new ExcelReportService();
                            //oldexcelService.GenerateReport(Path.Combine(reportPath, string.Format(olddetailFileName, md, leadBlockItem.ToList<Lead>()[0].LeadBlockCode, Utility.GetNumber(month), year)),
                            //    leadBlockItem.ToList<Lead>(), leadBlockItem.ToList<Lead>().Select(c => c.LeadBlockCode).Distinct().ToList<string>());

                            List<Lead> locationLeads = assignmentItem.Where(c => c.Latitude != "0.0000" && c.Longitude != "0.0000").ToList<Lead>();
                            //List<Lead> busLeads = leadBlockItem.Where(c => c.LeadType == "B" && c.Latitude != "0.0000" && c.Longitude != "0.0000").ToList<Lead>();
                            //List<Lead> alnLeads = leadBlockItem.Where(c => c.LeadType != "B" && c.Latitude != "0.0000" && c.Longitude != "0.0000").ToList<Lead>();
                            List<Lead> emptyLocationLeads = assignmentItem.Where(c => c.Latitude == "0.0000" || c.Longitude == "0.0000").ToList<Lead>();
                            //List<Lead> emptyLocationAlnLeads = assignmentItem.Where(c => c.LeadType != "B" && c.Latitude == "0.0000" && c.Longitude == "0.0000").ToList<Lead>();
                            List<Lead> optimizedLeads = new List<Lead>();
                            List<Lead> optimizedLocationLeads = new List<Lead>();
                            List<Lead> toOptimizedLeads = new List<Lead>();
                            List<Lead> toMatchLeads = new List<Lead>();

                            toMatchLeads = locationLeads.Where(c => (c.LeadType == "A" || c.LeadType == "L") && (c.PcLeadType == "S")).ToList<Lead>();
                            //toOptimizedLeads.AddRange(locationLeads.Where(c => (c.LeadType == "A" || c.LeadType == "L") && (c.PcLeadType == "P")).ToList<Lead>());

                            foreach (var item in locationLeads.Where(c => (c.LeadType == "A" || c.LeadType == "L") && (c.PcLeadType == "R" || c.PcLeadType == "P")).GroupBy(c => new { c.StreetAddress, c.LeadCity }))
                            {
                                //Logger.Info("Key is " + item.Key.LeadCity + "|" + item.Key.StreetAddress);
                                Lead lead = null;
                                if (item.Any(c => c.PcLeadType == "P"))
                                {
                                    lead = item.First<Lead>(c => c.PcLeadType == "P");
                                }
                                else
                                {
                                    lead = item.First<Lead>();
                                }

                                toOptimizedLeads.Add(lead);
                                toMatchLeads.AddRange(item.Where(c => c != lead).ToList<Lead>());
                            }

                            Logger.Info("toOptimizedLeads is " + toOptimizedLeads.Count);
                            Logger.Info("toMatchLeads is " + toMatchLeads.Count);

                            toOptimizedLeads.AddRange(locationLeads.Where(c => (c.LeadType == "N" || c.LeadType == "B")).ToList<Lead>());

                            if (toOptimizedLeads.Count >= 1000)
                            {
                                optimizedLocationLeads = toOptimizedLeads.OrderBy(c => c.StreetAddress).ToList<Lead>();
                                Logger.Warn("Skip optimize leads for assignment " + assignmentItem.Key);
                            }
                            else
                            {
                                optimizedLocationLeads = mappoint.CalculateRoute(toOptimizedLeads);
                            }

                            //optimizedLeads.AddRange(optimizedLocationLeads);
                            optimizedLocationLeads.AddRange(emptyLocationLeads);

                            int pos = 1;
                            foreach (var lead in optimizedLocationLeads)
                            {
                                lead.OptimizeCode = pos.ToString("D4");
                                optimizedLeads.Add(lead);

                                if (lead.LeadType == "A" || lead.LeadType == "L")
                                {
                                    List<Lead> matchedLeads = null;

                                    if (lead.PcLeadType == "P")
                                    {
                                        matchedLeads = toMatchLeads.Where(c => c.StreetAddress == lead.StreetAddress && c.LeadCity == lead.LeadCity).ToList<Lead>();
                                    }
                                    else
                                    {
                                        matchedLeads = toMatchLeads.Where(c => c.StreetAddress == lead.StreetAddress && c.LeadCity == lead.LeadCity && c.PcLeadType == "R").ToList<Lead>();
                                    }

                                    if (matchedLeads != null && matchedLeads.Count > 0)
                                    {
                                        foreach (var matchedLead in matchedLeads)
                                        {
                                            matchedLead.OptimizeCode = lead.OptimizeCode;
                                            optimizedLeads.Add(matchedLead);
                                            toMatchLeads.RemoveAll(c => c.LeadId == matchedLead.LeadId);
                                        }
                                    }
                                }

                                pos++;
                            }

                            if (toMatchLeads != null && toMatchLeads.Count > 0)
                            {
                                foreach (var lead in optimizedLocationLeads)
                                {
                                    if (lead.LeadType == "A" || lead.LeadType == "L")
                                    {
                                        List<Lead> matchedLeads = null;

                                        if (lead.PcLeadType == "P")
                                        {
                                            matchedLeads = toMatchLeads.Where(c => c.PcName == lead.PcName).ToList<Lead>();
                                        }

                                        if (matchedLeads != null && matchedLeads.Count > 0)
                                        {
                                            foreach (var matchedLead in matchedLeads)
                                            {
                                                matchedLead.OptimizeCode = lead.OptimizeCode;
                                                optimizedLeads.Add(matchedLead);
                                                toMatchLeads.RemoveAll(c => c.LeadId == matchedLead.LeadId);
                                            }
                                        }
                                    }
                                }
                            }

                            if (toMatchLeads != null && toMatchLeads.Count > 0)
                            {
                                foreach (var lead in toMatchLeads)
                                {
                                    lead.OptimizeCode = pos.ToString("D4");
                                    optimizedLeads.Add(lead);

                                    pos++;
                                }
                            }


                            //foreach (var lead in toMatchLeads)
                            //{
                            //    List<Lead> matchedLeads = optimizedLeads.Where(c => c.PcName == lead.PcName && c.StreetAddress == lead.StreetAddress && c.LeadCity == lead.LeadCity).ToList<Lead>();

                            //    if (matchedLeads != null && matchedLeads.Count > 0)
                            //    {
                            //        lead.OptimizeCode = matchedLeads[0].OptimizeCode;
                            //        int index = int.Parse(lead.OptimizeCode.TrimStart(new char[] { '0' }));
                            //    }
                            //}

                            optimizedLeads = optimizedLeads.OrderBy(c => c.OptimizeCode).ThenBy(c => c.IndividualName.Split(' ').Last<string>()).ToList<Lead>();

                            #region Generate files for DMRA

                            if (bool.Parse(ConfigurationManager.AppSettings["IsGenerateDMRA"]))
                            {
                                //Generate dmra file

                                foreach (Lead lead in optimizedLeads)
                                {
                                    if (!string.IsNullOrEmpty(lead.RawData))
                                    {
                                        string appendData = string.Empty;

                                        var agentItems = agents.Where(c => c.Name == lead.UserId.Substring(lead.UserId.IndexOf(' ') + 1)).ToList<Agent>();
                                        string agentCode = string.Empty;

                                        if (agentItems != null && agentItems.Count > 0)
                                        {
                                            agentCode = agentItems[0].AgentCode;
                                        }

                                        string assignCode = lead.UserId.Split(' ')[0] + agentCode;

                                        string weekCode = "     ";
                                        if (!string.IsNullOrEmpty(lead.UserId))
                                        {
                                            DateTime date = Utility.GetDayInMonth(CurrentPeriod.Year,
                                                CurrentPeriod.Month, DayOfWeek.Monday, int.Parse(lead.UserId.Split(' ')[0]));
                                            weekCode = date.Month.ToString().PadLeft(2, '0') + "/" + date.Day.ToString().PadLeft(2, '0');
                                        }

                                        List<string> cities = optimizedLeads.Select(c => c.PreferCity).Distinct().ToList<string>();

                                        string cityString = string.Empty;

                                        if (cities != null && cities.Count > 0)
                                        {
                                            for (int i = 0; i < cities.Count; i++)
                                            {
                                                cityString += cities[i];

                                                if (i != cities.Count - 1)
                                                {
                                                    cityString += ",";
                                                }
                                            }
                                        }

                                        appendData = lead.OptimizeCode + lead.UserId.PadRight(30) + assignCode.PadRight(6) + weekCode + cityString.PadRight(100).Substring(0, 100);

                                        if (lead.LeadType == "B" || lead.LeadType == "N")
                                        {
                                            prossw.WriteLine(lead.RawData + appendData);
                                        }
                                        else
                                        {
                                            basesw.WriteLine(lead.RawData + appendData);
                                        }

                                        //Generate hist file
                                        histsw.WriteLine(ConstructString(lead));
                                    }
                                }
                            }

                            #endregion

                            foreach (var lead in optimizedLeads)
                            {
                                lead.RawData = string.Empty;
                                pos++;
                            }

                            StringWriter writer = new StringWriter();
                            XmlSerializer serializer = new XmlSerializer(typeof(List<Lead>));
                            serializer.Serialize(writer, optimizedLeads);

                            new LeadAccessor().InsertOptimizedLead(md, optimizedLeads[0].UserId, writer.ToString(), optimizedLeads.Count,
                                optimizedLeads.Where(c => c.LeadType == "A" && c.PcLeadType != "R").Select(c => c.OptimizeCode).Distinct().Count(),
                                optimizedLeads.Where(c => c.LeadType == "L" && c.PcLeadType != "R").Select(c => c.OptimizeCode).Distinct().Count(),
                                optimizedLeads.Where(c => c.LeadType == "B").ToList<Lead>().Count,
                                optimizedLeads.Where(c => c.LeadType == "N").ToList<Lead>().Count);

                            if (writer != null)
                            {
                                writer.Dispose();
                            }

                            Logger.Info(string.Format("Optimized {0} lead blocks", number));
                            number++;
                        }
                    }


                    prossw.Flush();
                    prossw.Close();
                    basesw.Flush();
                    basesw.Close();
                    histsw.Flush();
                    histsw.Close();
                    basefs.Dispose();
                    prosfs.Dispose();
                    fs.Dispose();
                }

                if (mappoint != null)
                {
                    mappoint.Close();
                }

                Logger.Info("End optimize lead for " + md);
            }
        }

        private static void GenerateReport()
        {
            string mds = ConfigurationManager.AppSettings["Name"];
            int month = 0;
            int year = 0;

            GetMonthAndYear(out month, out year);

            const string detailFileName = "{0}_{1}_{2}{3}_DetailRpt.xls";
            const string blankDetailFileName = "{0}_{1}_{2}{3}_BlankRpt.xls";
            //const string olddetailFileName = "{0}_{1}_{2}{3}_DetailRpt_old.xls";
            //const string routeMapFileName = "RouteMap_{0}_{1}_{2}.pdf";
            const string overviewMapFileName = "OverviewMap_{0}_{1}.pdf";
            //const string dmraFileName = "Order_{0}{1}.txt";
            //const string histFileName = "OrderHist_{0}{1}.txt";
            string reportPath = "{0}/{1}/{2}/{3}";

            LeadManager leadManager = new LeadManager();
            MappointService mappoint = null;

            foreach (var md in mds.Split(','))
            {
                Logger.Info("Start generate reports for " + md);

                if (bool.Parse(ConfigurationManager.AppSettings["IsGenerateDetailReport"])
                    || bool.Parse(ConfigurationManager.AppSettings["IsGenerateMap"])
                    || bool.Parse(ConfigurationManager.AppSettings["IsAgentPotential"])
                    || bool.Parse(ConfigurationManager.AppSettings["IsPowerName"])
                    || bool.Parse(ConfigurationManager.AppSettings["IsGenerateBlankDetailReport"]))
                {
                    mappoint = new MappointService();
                    List<string> allLeads = new LeadAccessor().GetOptimizedLead(md);

                    foreach (var lead in allLeads)
                    {
                        List<Lead> optimizedLeads = new List<Lead>();
                        string leadString = lead;

                        try
                        {
                            using (StringReader sr = new StringReader(leadString))
                            {
                                XmlSerializer serializer = new XmlSerializer(typeof(List<Lead>));
                                optimizedLeads = serializer.Deserialize(sr) as List<Lead>;
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("Exception in deserialize ", ex);
                        }

                        foreach (var item in optimizedLeads)
                        {
                            item.UserId = item.UserId.Replace('/', ' ');
                        }

                        string folderPath = string.Format(reportPath,
                                ConfigurationManager.AppSettings["ReportPath"], optimizedLeads[0].Division, optimizedLeads[0].Market, optimizedLeads[0].UserId.Trim());
                        if (!Directory.Exists(folderPath))
                        {
                            Directory.CreateDirectory(folderPath);
                        }

                        #region Generate detail report

                        if (bool.Parse(ConfigurationManager.AppSettings["IsGenerateDetailReport"]))
                        {
                            //Generate optimized lead detail report file
                            //LeadBlock leadBlock = new ZipAccessor().GetLeadBlockByCode(optimizedLeads[0].LeadBlockCode);

                            ExcelReportService excelService = new ExcelReportService();
                            excelService.GenerateReport(Path.Combine(folderPath,
                                string.Format(detailFileName, md, optimizedLeads[0].UserId, month.ToString("D2"), year)), optimizedLeads, optimizedLeads[0].UserId);
                        }

                        #endregion

                        #region Generate blank detail report

                        if (bool.Parse(ConfigurationManager.AppSettings["IsGenerateBlankDetailReport"]))
                        {
                            ExcelReportService excelService = new ExcelReportService();
                            excelService.GenerateReport(Path.Combine(folderPath,
                                string.Format(blankDetailFileName, md, optimizedLeads[0].UserId, month.ToString("D2"), year)), optimizedLeads[0].UserId);
                        }

                        #endregion

                        #region Generate strip map

                        if (bool.Parse(ConfigurationManager.AppSettings["IsGenerateMap"]))
                        {
                            List<Lead> filterLeads = new List<Lead>();
                            foreach (var leadItem in optimizedLeads)
                            {
                                if (!(leadItem.PcLeadType == "S" && (leadItem.LeadType == "A" || leadItem.LeadType == "L")))
                                {
                                    filterLeads.Add(leadItem);
                                }
                            }

                            mappoint.GenerateOverviewMap(Path.Combine(folderPath, string.Format(overviewMapFileName, md, filterLeads[0].UserId)), filterLeads);

                            //Lead previosLead = null;
                            List<Lead> stripLeads = new List<Lead>();
                            //int seq = 1;

                            //Generate strip map
                            //foreach (var lead in optimizedLeads)
                            //{
                            //    stripLeads.Add(lead);
                            //    if (stripLeads.Count == 10)
                            //    {
                            //        //if (previosLead != null)
                            //        //{
                            //        //    stripLeads.Insert(0, previosLead);
                            //        //}
                            //        //previosLead = stripLeads[9];
                            //        mappoint.GenerateStripMap(Path.Combine(folderPath, string.Format(routeMapFileName, md, stripLeads[0].LeadBlockCode, seq)), stripLeads);


                            //        seq++;
                            //        stripLeads.Clear();
                            //    }
                            //}

                            //if (stripLeads.Count > 0)
                            //{
                            //    mappoint.GenerateStripMap(Path.Combine(folderPath, string.Format(routeMapFileName, md, stripLeads[0].LeadBlockCode, seq)), stripLeads);
                            //    stripLeads.Clear();
                            //}
                        }

                        #endregion

                        #region Generate agent potenial report

                        if (bool.Parse(ConfigurationManager.AppSettings["IsAgentPotential"]))
                        {
                            /*
                            Assignment assignment = new Assignment()
                            {
                                AgentName = optimizedLeads[0].UserId,
                                //ActiveLeadCount = optimizedLeads.Where(c => c.PcLeadType == "P" && c.PersonStatus == "A").ToList<Lead>().Count,
                                //LapsedLeadCount = optimizedLeads.Where(c => c.PcLeadType == "P" && c.PersonStatus == "L").ToList<Lead>().Count,
                                NeighborLeadCount = optimizedLeads.Where(c => c.LeadType == "N").ToList<Lead>().Count,
                                BusinessLeadCount = optimizedLeads.Where(c => c.LeadType == "B").ToList<Lead>().Count,
                            };

                            foreach (var item in optimizedLeads.GroupBy(c => c.LeadBlockCode))
                            {
                                List<Lead> groupLeads = item.ToList<Lead>();

                                if (groupLeads.Exists(c => c.PcLeadType == "P" && c.PersonStatus == "A")
                                    || groupLeads.Exists(c => c.PcLeadType == "P" && c.PersonStatus == "L"))
                                {
                                    assignment.ActiveLeadCount += groupLeads.Where(c => c.PcLeadType == "P" && c.PersonStatus == "A").ToList<Lead>().Count;
                                    assignment.LapsedLeadCount += groupLeads.Where(c => c.PcLeadType == "P" && c.PersonStatus == "L").ToList<Lead>().Count;
                                }
                                else
                                {
                                    assignment.ActiveLeadCount += groupLeads.Where(c => c.PcLeadType == "R" && c.PersonStatus == "A").ToList<Lead>().Count;
                                    assignment.LapsedLeadCount += groupLeads.Where(c => c.PcLeadType == "R" && c.PersonStatus == "L").ToList<Lead>().Count;
                                }

                            }
                            */

                            Assignment assignment = new Assignment()
                            {
                                AgentName = optimizedLeads[0].UserId,
                                ActiveLeadCount = optimizedLeads.Where(c => c.LeadType == "A" && c.PcLeadType != "R").Select(c => c.OptimizeCode).Distinct().Count(),
                                LapsedLeadCount = optimizedLeads.Where(c => c.LeadType == "L" && c.PcLeadType != "R").Select(c => c.OptimizeCode).Distinct().Count(),
                                NeighborLeadCount = optimizedLeads.Where(c => c.LeadType == "N").ToList<Lead>().Count,
                                BusinessLeadCount = optimizedLeads.Where(c => c.LeadType == "B").ToList<Lead>().Count,
                            };
                            ExcelReportService ers = new ExcelReportService();
                            ers.GenerateAgentPotentialReport(folderPath, md, month, year, assignment);
                        }

                        #endregion

                        #region Gernerate power name report

                        if (bool.Parse(ConfigurationManager.AppSettings["IsPowerName"]))
                        {
                            string assignmentName = optimizedLeads[0].UserId;
                            List<PowerName> names = new PowerManager().GetPowerNameList(assignmentName,
                                optimizedLeads.Select(c => c.LeadBlockCode.Substring(0, 5)).Distinct().ToList<string>());

                            if (names != null && names.Count > 0)
                            {
                                ExcelReportService ers = new ExcelReportService();
                                List<PowerName> toDoNames = new List<PowerName>();
                                int seq = 1;
                                foreach (var toDoName in names)
                                {
                                    toDoNames.Add(toDoName);

                                    if (toDoNames.Count == 10)
                                    {
                                        ers.GeneratePowerNameReport(Path.Combine(folderPath, string.Format("PowerNameReport_{0}_{1}.xls", assignmentName, seq)), toDoNames);
                                        toDoNames.Clear();
                                        seq++;
                                    }
                                }

                                if (toDoNames.Count > 0)
                                {
                                    ers.GeneratePowerNameReport(Path.Combine(folderPath, string.Format("PowerNameReport_{0}_{1}.xls", assignmentName, seq)), toDoNames);
                                    toDoNames.Clear();
                                }
                            }
                        }

                        #endregion
                    }
                }

                if (mappoint != null)
                {
                    mappoint.Close();
                }

                Logger.Info("End generate reports for " + md);
            }
        }

        private static void ReadXml()
        {
            XElement element = XElement.Load(@"c:\1.xml");

            string content = element.Element("Division").Element("Market").Element("Terrority").Element("LeadBlock").Element("OverviewMap").Value;
            byte[] fileBytes = Convert.FromBase64String(content);

            File.WriteAllBytes(@"c:\test.pdf", fileBytes);
        }

        private static void GenerateXml()
        {
            XElement element = new XElement("Order");
            element.Add(new XAttribute("Month", "11"));
            element.Add(new XAttribute("Year", "2010"));

            element.Add(new XElement("Division"));
            element.Element("Division").Add(new XElement("Market"));
            element.Element("Division").Element("Market").Add(new XElement("Terrority"));
            element.Element("Division").Element("Market").Element("Terrority").Add(new XElement("LeadBlock"));
            element.Element("Division").Element("Market").Element("Terrority").Element("LeadBlock").Add(new XAttribute("Number", "557446157"));
            element.Element("Division").Element("Market").Element("Terrority").Element("LeadBlock").Add(new XAttribute("MD", "GAMK"));

            string[] files = Directory.GetFiles(@"C:\report\44\01\557446157", "*.pdf");
            foreach (var file in files.OrderBy(c => c))
            {
                byte[] fileBytes = File.ReadAllBytes(file);
                string content = Convert.ToBase64String(fileBytes);

                if (file.IndexOf("AgentPotential", StringComparison.InvariantCultureIgnoreCase) != -1)
                {
                    element.Element("Division").Element("Market").Element("Terrority").Element("LeadBlock").Add(new XElement("Potential"));
                    element.Element("Division").Element("Market").Element("Terrority").Element("LeadBlock").Element("Potential").Value = content;
                }
                else if (file.IndexOf("RouteMap", StringComparison.InvariantCultureIgnoreCase) != -1)
                {
                    element.Element("Division").Element("Market").Element("Terrority").Element("LeadBlock").Add(new XElement("StripMaps"));
                    element.Element("Division").Element("Market").Element("Terrority").Element("LeadBlock").Elements("StripMaps").Last().Value = content;
                }
                else if (file.IndexOf("OverviewMap", StringComparison.InvariantCultureIgnoreCase) != -1)
                {
                    element.Element("Division").Element("Market").Element("Terrority").Element("LeadBlock").Add(new XElement("OverviewMap"));
                    element.Element("Division").Element("Market").Element("Terrority").Element("LeadBlock").Element("OverviewMap").Value = content;
                }
                else
                {
                    // Nothing to do
                }
            }

            File.WriteAllText(@"c:\1.xml", element.ToString());
        }

        private static List<PowerName> GetPowerNameData(string path)
        {
            List<PowerName> names = new List<PowerName>();
            int i = 0;
            string errorline = string.Empty;

            try
            {
                Logger.Info("Begin parse file at " + path);

                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    StreamReader sr = new StreamReader(fs);

                    for (string line = sr.ReadLine(); line != null; line = sr.ReadLine())
                    {
                        if (!string.IsNullOrEmpty(line))
                        {
                            if (i != 0)
                            {
                                int startIndex = line.IndexOf(",\"");
                                int endIndex = line.IndexOf("\",");
                                List<string> infos = new List<string>();
                                errorline = line;

                                if (startIndex != -1 && endIndex != -1)
                                {
                                    if (endIndex - startIndex == 1)
                                    {
                                        endIndex = line.IndexOf("\",", endIndex + 1);
                                    }

                                    infos.AddRange(line.Substring(0, startIndex).Split(','));
                                    string firmName = (endIndex - startIndex - 2) == 0 ? string.Empty : line.Substring(startIndex + 2, endIndex - startIndex - 2);
                                    infos.Add(firmName);
                                    infos.AddRange(line.Substring(endIndex + 2).Split(','));
                                }
                                else
                                {
                                    infos.AddRange(line.Split(','));
                                }

                                if (infos.Count == 10)
                                {
                                    PowerName powerName = new PowerName()
                                    {
                                        FirstName = infos[0],
                                        LastName = infos[1],
                                        FirmName = infos[2],
                                        BusResCity = infos[3],
                                        Occupation = infos[4],
                                        Tenure = int.Parse(infos[5]),
                                        BusResZIP = infos[6],
                                        Division = infos[7],
                                        Market = infos[8],
                                        Terr = infos[9],
                                    };

                                    names.Add(powerName);
                                }
                                else
                                {
                                    Logger.Warn("Incorrect line:" + line);
                                }
                            }

                            i++;
                        }
                    }
                }

                Logger.Info(string.Format("{0} records are collected", i - 1));
                Logger.Info("End parse file at " + path);
            }
            catch (Exception ex)
            {
                Logger.Error("Exception in get powername data at " + path + errorline, ex);
            }

            return names;
        }

        private static bool MeragePDF(List<string> inputFiles, string outputFile)
        {
            bool result = true;

            try
            {
                CAcroApp acroApp = new AcroAppClass();
                CAcroPDDoc doc = new AcroPDDocClass();
                CAcroPDDoc insertDoc = new AcroPDDocClass();

                result = doc.Create();

                foreach (var file in inputFiles)
                {
                    result = insertDoc.Open(file);
                    result = doc.InsertPages(doc.GetNumPages() - 1, insertDoc, 0, insertDoc.GetNumPages(), 0);
                    result = insertDoc.Close();
                }

                result = doc.Save(1, outputFile);
                result = doc.Close();
                result = acroApp.Exit();
                /*
                if (inputFiles != null && inputFiles.Count > 0 && !string.IsNullOrEmpty(outputFile))
                {
                    PdfReader reader;

                    Document document = new Document();

                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFile, FileMode.Create));

                    document.Open();

                    PdfContentByte cb = writer.DirectContent;

                    PdfImportedPage newPage;

                    for (int i = 0; i < inputFiles.Count; i++)
                    {

                        reader = new PdfReader(inputFiles[i]);

                        int iPageNum = reader.NumberOfPages;

                        for (int j = 1; j <= iPageNum; j++)
                        {

                            document.NewPage();

                            newPage = writer.GetImportedPage(reader, j);

                            if (inputFiles[i].IndexOf("power", StringComparison.InvariantCultureIgnoreCase) == -1
                                && inputFiles[i].IndexOf("PostcardTalkingPoints", StringComparison.InvariantCultureIgnoreCase) == -1)
                            {
                                cb.AddTemplate(newPage, -1f, 0, 0, -1f, newPage.Width, newPage.Height);
                            }
                            else
                            {
                                cb.AddTemplate(newPage, 1f, 0, 0, 1f, 0, 0);
                            }
                        }

                    }

                    document.Close();
                }
                 */
            }
            catch (Exception ex)
            {
                Logger.Error("Exception in merage PDF", ex);
                result = false;
            }

            return result;
        }

        private static string ConstructString(Lead lead)
        {
            StringBuilder data = new StringBuilder(string.Empty);
            data.Append(lead.SelPersonId.PadRight(9));
            data.Append(lead.LeadType.PadRight(1));
            data.Append(lead.SequenceNumber.PadRight(9));
            data.Append(lead.Division.PadRight(2));
            data.Append(lead.Market.PadRight(2));
            data.Append(lead.Zip.PadRight(9));
            data.Append(lead.LeadState.PadRight(2));
            //data.Append(lead.UserId.PadRight(30));

            return data.ToString();
        }

        private static void ScanFolder(string path)
        {
            string[] folders = Directory.GetDirectories(path);

            if (folders == null || folders.Length == 0)
            {
                //totalCount += Directory.GetFiles(path).Count();
                string[] files = Directory.GetFiles(path, "*.pdf");
                if (files != null && files.Count() > 0)
                {
                    DirectoryInfo folder = new DirectoryInfo(path);
                    string outFile = Path.Combine(path, folder.Name + ".pdf");

                    if (File.Exists(outFile))
                    {
                        File.Delete(outFile);
                        Logger.Info("Delete exist meraged file at " + outFile);
                    }

                    List<string> inputFiles = new List<string>();
                    inputFiles.AddRange(files.Where(c => c.Contains("AgentPotential")));
                    inputFiles.AddRange(files.Where(c => c.Contains("DetailRpt")));
                    inputFiles.AddRange(files.Where(c => c.Contains("PowerName")));
                    //inputFiles.Add(Environment.CurrentDirectory + @"\PostcardTalkingPoints.pdf");
                    inputFiles.AddRange(files.Where(c => c.Contains("OverviewMap")));
                    inputFiles.AddRange(files.Where(c => c.Contains("RouteMap")));

                    MeragePDF(inputFiles, outFile);

                    if (bool.Parse(ConfigurationManager.AppSettings["IsNeedDeleteFile"]))
                    {
                        foreach (var file in Directory.GetFiles(path).Where(c => c != outFile))
                        {
                            File.Delete(file);
                            Logger.Info("Delete file at " + outFile);
                        }
                    }
                }
                else
                {
                    //Directory.Delete(path);
                }
            }
            else
            {
                foreach (var folder in folders)
                {
                    ScanFolder(folder);
                }
            }
        }

        private static void MergeTxt(string path)
        {
            int month = 0;
            int year = 0;

            GetMonthAndYear(out month, out year);

            const string dmraFileNameOfBase = "Base{0}{1}.txt";
            const string dmraFileNameOfPros = "Pros{0}{1}.txt";
            const string histFileName = "OrderHist{0}{1}.txt";

            string[] files = Directory.GetFiles(path, "*.txt");

            FileStream baseStream = new FileStream(Path.Combine(path, string.Format(dmraFileNameOfBase, month.ToString("D2"), year)), FileMode.Create);
            FileStream prosStream = new FileStream(Path.Combine(path, string.Format(dmraFileNameOfPros, month.ToString("D2"), year)), FileMode.Create);
            FileStream histStream = new FileStream(Path.Combine(path, string.Format(histFileName, month.ToString("D2"), year)), FileMode.Create);
            StreamWriter baseWriter = new StreamWriter(baseStream);
            StreamWriter prosWriter = new StreamWriter(prosStream);
            StreamWriter histWriter = new StreamWriter(histStream);

            foreach (var file in files)
            {
                if (file.IndexOf(month.ToString("D2") + year.ToString()) > -1)
                {
                    int count = 0;
                    using (FileStream fs = new FileStream(file, FileMode.Open))
                    {
                        StreamReader sr = new StreamReader(fs);

                        for (string line = sr.ReadLine(); line != null; line = sr.ReadLine())
                        {
                            count++;
                            if (file.IndexOf("Base") > -1)
                            {
                                baseWriter.WriteLine(line);
                            }
                            if (file.IndexOf("Pros") > -1)
                            {
                                prosWriter.WriteLine(line);
                            }
                            if (file.IndexOf("OrderHist") > -1)
                            {
                                histWriter.WriteLine(line);
                            }
                        }
                    }

                    Logger.Info(string.Format("{0} contains {1} records.", file, count));
                }
            }

            baseWriter.Close();
            prosWriter.Close();
            histWriter.Close();
            baseStream.Dispose();
            prosStream.Dispose();
            histStream.Dispose();

            #region Encrypt

            FileStream input = null;
            FileStream output = null;
            GnuPG gnu = new GnuPG();
            gnu.Recipient = SystemConfiguration.CommonSetting.PrintingHouseRecipient;

            input = new FileStream(Path.Combine(path, string.Format(dmraFileNameOfBase, month.ToString("D2"), year)), FileMode.Open);
            output = new FileStream(Path.Combine(path, string.Format(dmraFileNameOfBase, month.ToString("D2"), year) + ".pgp"), FileMode.Create);
            gnu.Encrypt(input, output);

            input = new FileStream(Path.Combine(path, string.Format(dmraFileNameOfPros, month.ToString("D2"), year)), FileMode.Open);
            output = new FileStream(Path.Combine(path, string.Format(dmraFileNameOfPros, month.ToString("D2"), year) + ".pgp"), FileMode.Create);
            gnu.Encrypt(input, output);

            input = new FileStream(Path.Combine(path, string.Format(histFileName, month.ToString("D2"), year)), FileMode.Open);
            output = new FileStream(Path.Combine(path, string.Format(histFileName, month.ToString("D2"), year) + ".pgp"), FileMode.Create);
            gnu.Encrypt(input, output);

            #endregion

            #region Upload

            #endregion
        }

        private static void GenerateTxt()
        {
            string mds = ConfigurationManager.AppSettings["Name"];
            int month = CurrentPeriod.Month;
            int year = CurrentPeriod.Year;
            const string dmraFileNameOfBase = "Base_{0}_{1}{2}.txt";
            const string dmraFileNameOfPros = "Pros_{0}_{1}{2}.txt";
            const string histFileName = "OrderHist_{0}_{1}{2}.txt";

            foreach (var md in mds.Split(','))
            {
                Logger.Info("Start generate txt for " + md);

                List<string> allLeads = new LeadAccessor().GetOptimizedLead(md);
                List<Agent> agents = new AccountManager().GetAgents(md);
                FileStream basefs = new FileStream(Path.Combine(ConfigurationManager.AppSettings["ReportPath"], string.Format(dmraFileNameOfBase, md, month.ToString("D2"), year)), FileMode.Create);
                FileStream prosfs = new FileStream(Path.Combine(ConfigurationManager.AppSettings["ReportPath"], string.Format(dmraFileNameOfPros, md, month.ToString("D2"), year)), FileMode.Create);
                FileStream fs = new FileStream(Path.Combine(ConfigurationManager.AppSettings["ReportPath"], string.Format(histFileName, md, month.ToString("D2"), year)),
                            FileMode.Create);
                StreamWriter basesw = new StreamWriter(basefs);
                StreamWriter prossw = new StreamWriter(prosfs);
                StreamWriter histsw = new StreamWriter(fs);

                foreach (var leadS in allLeads)
                {
                    List<Lead> optimizedLeads = new List<Lead>();
                    string leadString = leadS;

                    try
                    {
                        using (StringReader sr = new StringReader(leadString))
                        {
                            XmlSerializer serializer = new XmlSerializer(typeof(List<Lead>));
                            optimizedLeads = serializer.Deserialize(sr) as List<Lead>;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Exception in deserialize ", ex);
                    }

                    #region Generate files for DMRA

                    if (bool.Parse(ConfigurationManager.AppSettings["IsGenerateDMRA"]))
                    {
                        //Generate dmra file

                        Logger.Info("Optimized:" + optimizedLeads.Count.ToString());

                        foreach (var lead in optimizedLeads)
                        {
                            lead.RawData = new LeadAccessor().GetRawData(lead);
                        }

                        foreach (Lead lead in optimizedLeads)
                        {
                            if (!string.IsNullOrEmpty(lead.RawData))
                            {
                                string appendData = string.Empty;

                                Agent agent = agents.Where(c => c.Name == lead.UserId.Substring(lead.UserId.IndexOf(' ') + 1)).First();
                                string assignCode = lead.UserId.Split(' ')[0] + agent.AgentCode;

                                string weekCode = "     ";
                                if (!string.IsNullOrEmpty(lead.UserId))
                                {
                                    DateTime date = Utility.GetDayInMonth(CurrentPeriod.Year,
                                        CurrentPeriod.Month, DayOfWeek.Monday, int.Parse(lead.UserId.Split(' ')[0]));
                                    weekCode = date.Month.ToString().PadLeft(2, '0') + "/" + date.Day.ToString().PadLeft(2, '0');
                                }

                                List<string> cities = optimizedLeads.Select(c => c.PreferCity).Distinct().ToList<string>();

                                string cityString = string.Empty;

                                if (cities != null && cities.Count > 0)
                                {
                                    for (int i = 0; i < cities.Count; i++)
                                    {
                                        cityString += cities[i];

                                        if (i != cities.Count - 1)
                                        {
                                            cityString += ",";
                                        }
                                    }
                                }

                                appendData = lead.OptimizeCode + lead.UserId.PadRight(30) + assignCode.PadRight(6) + weekCode + cityString.PadRight(100);

                                if (lead.LeadType == "B" || lead.LeadType == "N")
                                {
                                    prossw.WriteLine(lead.RawData + appendData);
                                }
                                else
                                {
                                    basesw.WriteLine(lead.RawData + appendData);
                                }

                                if (!string.IsNullOrEmpty(lead.RawData))
                                {
                                    histsw.WriteLine(ConstructString(lead));
                                }
                            }
                        }
                    }

                    #endregion
                }

                prossw.Flush();
                prossw.Close();
                basesw.Flush();
                basesw.Close();
                histsw.Flush();
                histsw.Close();
                basefs.Dispose();
                prosfs.Dispose();
                fs.Dispose();
            }
        }

        private static List<string> ConvertToCSV(string file)
        {
            List<string> files = new List<string>();
            Microsoft.Office.Interop.Excel.Application excelApplication = null;
            Workbooks workBooks = null;
            Workbook workBook = null;
            Worksheet workSheet = null;
            Range rans = null;
            Range ran = null;

            try
            {
                object o = System.Reflection.Missing.Value;
                excelApplication = new Microsoft.Office.Interop.Excel.Application();
                excelApplication.Visible = false;
                workBooks = excelApplication.Workbooks;
                workBook = workBooks.Open(file, o, o, o, o, o, o, o, o, o, o, o, o, o, o);
                int index = 0;

                foreach (var sheet in workBook.Sheets)
                {
                    string destPath = file.Replace(".xls", "_" + index.ToString() + ".csv");
                    if (File.Exists(destPath))
                    {
                        File.Delete(destPath);
                    }

                    index++;
                    workSheet = (Worksheet)sheet;
                    workSheet.SaveAs(destPath,
                        XlFileFormat.xlCSV, o, o, o, o, o, o, o, o);

                    files.Add(destPath);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception in get convert to csv at " + file, ex);
            }
            finally
            {
                #region Release the excel related object
                if (ran != null)
                {
                    Marshal.ReleaseComObject(ran);
                    rans = null;
                }

                if (rans != null)
                {
                    Marshal.ReleaseComObject(rans);
                    rans = null;
                }

                if (workSheet != null)
                {
                    Marshal.ReleaseComObject(workSheet);
                    workSheet = null;
                }

                if (workBook != null)
                {
                    workBook.Close(false, Type.Missing, Type.Missing);
                    Marshal.ReleaseComObject(workBook);
                    workBook = null;
                }

                if (workBooks != null)
                {
                    workBooks.Close();
                    Marshal.ReleaseComObject(workBooks);
                    workBooks = null;
                }

                if (excelApplication != null)
                {
                    excelApplication.Quit();
                }

                IntPtr point = new IntPtr(excelApplication.Hwnd);
                int processId = 0;
                GetWindowThreadProcessId(point, out processId);
                Process p = Process.GetProcessById(processId);
                p.Kill();

                #endregion
            }

            return files;
        }

        private static void SendSummaryReportPerMD()
        {
            int month = 0;
            int year = 0;

            AKMII.DMRA.Common.Constants.ExcelReportPath = ConfigurationManager.AppSettings["ReportPath2"];
            GetMonthAndYear(out month, out year);
            List<User> users = new UserAccessor().GetAllUsers(0, 0);
            Dictionary<string, int> leadCountGroup = new Dictionary<string, int>();
            Dictionary<string, int> activeInfoPerDivMkt = new Dictionary<string, int>();
            Dictionary<string, int> lapsedInfoPerDivMkt = new Dictionary<string, int>();

            foreach (var user in users)
            {
                List<string> allLeads = new LeadAccessor().GetOptimizedLead(user.Id);
                List<Lead> leads = new List<Lead>();
                Dictionary<string, int> activeInfoPerCode = new Dictionary<string, int>();
                Dictionary<string, int> lapsedInfoPerCode = new Dictionary<string, int>();

                if (allLeads != null && allLeads.Count > 0)
                {
                    Logger.Info("Start generate summary confirmation report for " + user.Id);

                    foreach (var lead in allLeads)
                    {
                        List<Lead> optimizedLeads = new List<Lead>();
                        string leadString = lead;

                        try
                        {
                            using (StringReader sr = new StringReader(leadString))
                            {
                                XmlSerializer serializer = new XmlSerializer(typeof(List<Lead>));
                                optimizedLeads = serializer.Deserialize(sr) as List<Lead>;

                                foreach (var item in optimizedLeads.Where(c => c.LeadType == "A").GroupBy(c => c.OptimizeCode))
                                {
                                    Lead firstLead = item.First<Lead>();

                                    if (activeInfoPerCode.ContainsKey(firstLead.LeadBlockCode))
                                    {
                                        activeInfoPerCode[firstLead.LeadBlockCode] += 1;
                                    }
                                    else
                                    {
                                        activeInfoPerCode[firstLead.LeadBlockCode] = 1;
                                    }
                                }

                                foreach (var item in optimizedLeads.Where(c => c.LeadType == "L").GroupBy(c => c.OptimizeCode))
                                {
                                    Lead firstLead = item.First<Lead>();

                                    if (lapsedInfoPerCode.ContainsKey(firstLead.LeadBlockCode))
                                    {
                                        lapsedInfoPerCode[firstLead.LeadBlockCode] += 1;
                                    }
                                    else
                                    {
                                        lapsedInfoPerCode[firstLead.LeadBlockCode] = 1;
                                    }
                                }

                                leads.AddRange(optimizedLeads);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("Exception in deserialize ", ex);
                        }
                    }

                    List<LeadBlock> codes = new ZipAccessor().GetLeadBlock(user.Id, month, year);

                    foreach (var code in codes)
                    {
                        code.ActiveLeadCount = activeInfoPerCode.ContainsKey(code.LeadBlockCode) ? activeInfoPerCode[code.LeadBlockCode] : 0;
                        code.LapsedLeadCount = lapsedInfoPerCode.ContainsKey(code.LeadBlockCode) ? lapsedInfoPerCode[code.LeadBlockCode] : 0;

                        string key = code.UserId + "," + code.Division + "," + code.Market;

                        if (activeInfoPerDivMkt.ContainsKey(key))
                        {
                            activeInfoPerDivMkt[key] += code.ActiveLeadCount;
                            lapsedInfoPerDivMkt[key] += code.LapsedLeadCount;
                        }
                        else
                        {
                            activeInfoPerDivMkt[key] = code.ActiveLeadCount;
                            lapsedInfoPerDivMkt[key] = code.LapsedLeadCount;
                        }
                    }

                    new ReportManager().GenerateReport(codes, user.Id, month, year);
                }
            }

            List<OrderInfo> orderInfos = new OrderAccessor().GetOrderMoreInfo(month, year);

            foreach (var orderInfo in orderInfos)
            {
                string key = orderInfo.MdNumber + "," + orderInfo.Division + "," + orderInfo.Market;
                orderInfo.ActiveStopCount = activeInfoPerDivMkt.ContainsKey(key) ? activeInfoPerDivMkt[key] : 0;
                orderInfo.LapsedStopCount = lapsedInfoPerDivMkt.ContainsKey(key) ? lapsedInfoPerDivMkt[key] : 0;
            }

            string path = Path.Combine(ConfigurationManager.AppSettings["ReportPath"],
                        string.Format("Order_Information_{0}{1}.xls", Utility.GetNumber(month), Utility.GetNumber(year)));
            new ExcelReportService().GenerateReport(orderInfos, path);

            Mail mail = new Mail();
            mail.Subject = "Order Infomation";
            mail.Content = "Please check the attachment for Order Information Report.";
            mail.Recipients = new List<string>() { SystemConfiguration.CommonSetting.MailAddressForSummaryReport };
            mail.AttachmentFile = path;

            var mailService = new SmtpMailService(SystemConfiguration.CommonSetting.SmtpServer, SystemConfiguration.CommonSetting.SystemMailAddress,
                SystemConfiguration.CommonSetting.MailPassword);
            mailService.Send(mail);
        }

        private static void GetMonthAndYear(out int month, out int year)
        {
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["Month"]))
            {
                month = CurrentPeriod.Month;
            }
            else
            {
                month = int.Parse(ConfigurationManager.AppSettings["Month"]);
            }

            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["Year"]))
            {
                year = CurrentPeriod.Year;
            }
            else
            {
                year = int.Parse(ConfigurationManager.AppSettings["Year"]);
            }
        }

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern int GetWindowThreadProcessId(IntPtr hwnd, out   int ID);
    }
}
